import { safeIndexApi } from '@/api';
import { request } from '@/api/request';
import { Form, Spin } from 'antd';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';
import { getGrade } from './data';
type RecordType = any;
const SafeDriverList = () => {
  const navigator = useNavigate();
  const [form] = Form.useForm();
  const [tableDep, _reFreshTable] = useState<number>();
  const [searchParams, setEventParams] = useState({
    startTime: '',
    endTime: '',
  });
  const [totalNum, setTotalNum] = useState<any>(0);
  const [cardList, setCardList] = useState<any>([]);
  const [startList, setStartList] = useState<any>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const getCardList = () => {
    setLoading(true);
    safeIndexApi
      .starRatingStatisticsApi({ belongEntNames: form.getFieldsValue().belongEntNames || '' })
      .then((res: any) => {
        if (res.code == 200) {
          setTotalNum(res.data.totalNum);
          // 返回的统计和配置做合并,没在统计的星级，push进去
          const resList = [...res.data.starRatingList];
          startList.forEach((el: any) => {
            const hasRating = resList.some((item: any) => item.starRating == el.value);
            if (!hasRating) resList.push({ starRating: el.value, num: 0 });
          });
          resList.sort((a: any, b: any) => b.starRating - a.starRating);
          setCardList(resList);
          setLoading(false);
        }
      });
  };
  const getStartlistFn = () => {
    getGrade().then((res: any) => {
      if (res.code == 200) {
        const newArr: any[] = [];
        res.data.forEach((el: any) => {
          newArr.push(el.starRating);
        });
        const uniqueArr = Array.from(new Set(newArr));
        const arrnew = uniqueArr.map((el: any) => {
          return { value: el, label: el + '星' };
        });
        arrnew.sort((a: any, b: any) => b.value - a.value);
        setStartList(arrnew);
      }
    });
  };
  useEffect(() => {
    if (startList.length > 0) {
      getCardList();
    }
  }, [startList]);
  const [columns] = useState<YmColumnsType<RecordType>>([
    {
      title: '司机姓名',
      dataIndex: 'driverName',
      ellipsis: true,
      key: 'driverName',
      render(value, record, index) {
        return (
          <span
            className="safe-edu_table_operation_text"
            onClick={() => {
              navigator(
                `/safeIndex/safeIndexStatistics/driverIndexInfo?driverName=${value}&driverId=${record.driverId}`,
              );
            }}
          >
            {value}
          </span>
        );
      },
    },
    {
      title: '安全指数',
      dataIndex: 'safetyIndex',
      key: 'safetyIndex',
      ellipsis: true,
      render: (text, record) => <span>{text.toFixed(0) || '--'}</span>,
      sorter: true,
    },
    {
      title: '司机星级',
      dataIndex: 'starRating',
      key: 'starRating',
      ellipsis: true,
      render: (text, record) => <span>{text || '--'} 星</span>,
      sorter: true,
    },
    {
      title: '所属企业',
      dataIndex: 'belongEntNames',
      key: 'belongEntNames',
      ellipsis: true,
      render: (text, record) => <span>{text || '--'}</span>,
    },
    {
      title: '手机号',
      dataIndex: 'driverPhone',
      key: 'driverPhone',
      ellipsis: true,
    },

    {
      title: '实名',
      dataIndex: 'verifiedStatus',
      ellipsis: true,
      key: 'verifiedStatus',
      render: (text, record) => <span>{text == 1 ? '审核中' : text == 2 ? '已认证' : '未认证'}</span>,
    },
    {
      title: '驾驶证',
      dataIndex: 'drivingLicenseStatus',
      key: 'drivingLicenseStatus',
      ellipsis: true,
      render: (text, record) => <span>{text == 1 ? '审核中' : text == 2 ? '已认证' : '未认证'}</span>,
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      key: 'createTime',
      ellipsis: true,
    },
    // {
    //   title: '操作',
    //   key: 'action',
    //   width: 60,
    //   fixed: 'right',
    //   render: (_text, record) => {
    //     return (
    //       <Space direction="horizontal" size={0}>
    //         <Button
    //           type="text"
    //           size="small"
    //           onClick={(e: React.MouseEvent) => {
    //             // console.log(record, '123');
    //             // e.stopPropagation();
    //             // setCurCardId(record.studyCardId);
    //             // // setCurrPlanType(record.type);
    //             // setDrawerOpen(true);
    //           }}
    //         >
    //           <span className="safe-edu_table_operation_text">对比</span>
    //         </Button>
    //       </Space>
    //     );
    //   },
    // },
  ]);

  return (
    <div className="safe_boss_page">
      <div>
        <Spin spinning={loading}>
          <div style={{ display: 'flex', width: '100%', margin: '20px' }}>
            <div
              style={{
                width: '200px',
                height: '100px',
                marginRight: '20px',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                border: '1px solid #f0f0f0',
                borderRadius: '4px',
              }}
            >
              <span style={{ fontSize: '40px', marginRight: '5px' }}>{totalNum}</span>
              全部
            </div>
            {cardList.map((el: any, index: number) => {
              return (
                <div
                  key={index}
                  style={{
                    width: '200px',
                    height: '100px',
                    marginRight: '20px',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    border: '1px solid #f0f0f0',
                    borderRadius: '4px',
                  }}
                >
                  <span style={{ fontSize: '40px', marginRight: '5px' }}>{el.num}</span>位{el.starRating}星司机
                </div>
              );
            })}
          </div>
        </Spin>
        <YmTable
          searchForm={{
            formItems: [
              {
                label: '所属企业',
                name: 'belongEntNames',
                valueType: {
                  type: 'input',
                  inputProps: {
                    placeholder: '请输入',
                    autoComplete: 'off',
                  },
                },
              },
              {
                label: '司机姓名',
                name: 'driverName',
                valueType: {
                  type: 'input',
                  inputProps: {
                    placeholder: '请输入',
                    autoComplete: 'off',
                  },
                },
              },
              {
                label: '司机手机号',
                labelCol: {
                  style: { width: '100px' },
                },
                name: 'driverPhone',
                valueType: {
                  type: 'input',
                  inputProps: {
                    placeholder: '请输入',
                    autoComplete: 'off',
                  },
                },
              },
              {
                label: '实名认证',
                name: 'verifiedStatus',
                valueType: {
                  type: 'select',
                  selectProps: {
                    allowClear: true,
                    placeholder: '所有',
                    options: [
                      {
                        value: '',
                        label: '所有',
                      },
                      {
                        value: 2,
                        label: '已认证',
                      },
                      {
                        value: 4,
                        label: '未认证',
                      },
                      {
                        value: 1,
                        label: '审核中',
                      },
                    ],
                  },
                },
              },
              {
                label: '司机星级',
                labelCol: {
                  style: { width: '100px' },
                },
                name: 'starRating',
                valueType: {
                  type: 'select',
                  selectProps: {
                    allowClear: true,
                    placeholder: '所有',
                    options: startList,
                  },
                },
              },
            ],
            form,
            span: 6,
          }}
          columns={columns}
          request={async ({ page, sorter }, form) => {
            const options: { orderSort?: string; orderBy?: string } = { orderBy: '', orderSort: '' };

            // NOTE: orderBy -  1-安全指数 2-司机星级
            if (!Array.isArray(sorter)) {
              const { columnKey, order } = sorter ?? {};

              if (!order) {
                options.orderBy = '';
                options.orderSort = '';
              } else {
                if (columnKey === 'safetyIndex') {
                  options.orderBy = '1';
                  options.orderSort = order === 'ascend' ? 'asc' : order === 'descend' ? 'desc' : 'desc';
                } else if (columnKey === 'starRating') {
                  options.orderBy = '2';
                  options.orderSort = order === 'ascend' ? 'asc' : order === 'descend' ? 'desc' : 'desc';
                }
              }
            }

            const { data } = await request<{ list: any[]; total: number }>({
              url: '/unicron/ent/safetyIndex/driverList',
              data: {
                ...searchParams,
                ...options,
                ...page,
                ...form,
              },
            });
            // getCardList();
            getStartlistFn();
            return data;
          }}
          operate={[
            {
              text: '对比',
              key: 'compare',
              onClick: (record) => {
                navigator(
                  `/safeIndex/safeIndexStatistics/safeDriverComparison?driverId=${
                    record.driverId
                  }&driverObj=${JSON.stringify(record)}#part-1`,
                );
              },
            },
          ]}
          requestOptions={{
            reFreshDep: [tableDep],
            defaultPageSize: 10,
          }}
          rowKey="safetyIndexDriverId"
        />
      </div>
    </div>
  );
};
export default SafeDriverList;
